<template>
  <div class="home">
    <el-container>
      <el-header>
        <span
          style="
            color: white;
            line-height: 70px;
            width: 300px;
            font-weight: bold;
            font-size: 30px;
          "
          >川轻化校园互助平台</span
        >
        <div>
          <el-dropdown>
            <div>
              <!-- <el-avatar
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
              ></el-avatar> -->
                 <el-avatar> {{userName}} </el-avatar>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-plus"
                @click.native="registerFormVisible = true"
                >注册</el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-edit" @click.native="changeUser()" v-if="userName != null"
                >修改个人信息</el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-moon-night" @click.native="exit()"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-container style="height: calc(100% - 70px)">
        <el-aside width="200px">
          <el-menu
            default-active="2"
            class="el-menu-vertical-demo"
            background-color="#d6e6d5"
          >
            <el-menu-item index="1">
              <template>
                <router-link to="/home/barter">
                  <i class="el-icon-location"></i>
                  <span>寻物与出物</span>
                </router-link>
              </template>
            </el-menu-item>
            <el-menu-item index="2">
              <router-link to="/home/take">
                <i class="el-icon-location"></i>
                <span>代取物品</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="3">
              <router-link to="/home/share">
                <i class="el-icon-location"></i>
                <span>风景美食分享</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="5">
              <router-link to="/home/message">
                <i class="el-icon-location"></i>
                <span>留言板</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="6">
              <router-link to="/home/mine">
                <i class="el-icon-location"></i>
                <!-- <span>我的</span> -->
                <span>个人模块</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="7" v-if="flag">
              <router-link to="/home/admin">
                <i class="el-icon-location"></i>
                <span>管理员</span>
              </router-link>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
    <el-dialog title="注册" :visible.sync="registerFormVisible">
      <el-form
        :model="registerForm"
        :rules="rules"
        ref="registerForm"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="账号" prop="name">
          <el-input v-model="registerForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="registerForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="IdCard">
          <el-input
            v-model="registerForm.IdCard"
            autocomplete="off"
            onkeyup="this.value=this.value.replace(/[^\X0-9]/g, '')"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="registerFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="register('registerForm', registerForm)"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="修改用户信息" :visible.sync="changeFormVisible">
      <el-form
        :model="changeForm"
        :rules="rules"
        ref="changeForm"
        label-width="140px"
        label-position="right"
      >
        <el-form-item label="账号" prop="name">
          <el-input v-model="changeForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="此处修改密码" prop="pass">
          <el-input
            type="text"
            v-model="changeForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="changeForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update('changeForm', changeForm)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    var checkIdentitytionId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("身份证号不能为空"));
      }
      if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error("你输入的身份证长度或格式错误"));
      }
      //身份证城市
      var aCity = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外",
      };
      if (!aCity[parseInt(value.substr(0, 2))]) {
        callback(new Error("你的身份证地区非法"));
      }
      // 出生日期验证
      var sBirthday = (
          value.substr(6, 4) +
          "-" +
          Number(value.substr(10, 2)) +
          "-" +
          Number(value.substr(12, 2))
        ).replace(/-/g, "/"),
        d = new Date(sBirthday);
      if (
        sBirthday !=
        d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
      ) {
        callback(new Error("身份证上的出生日期非法"));
      }

      // 身份证号码校验
      var sum = 0,
        weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
        codes = "10X98765432";
      for (var i = 0; i < value.length - 1; i++) {
        sum += value[i] * weights[i];
      }
      var last = codes[sum % 11]; //计算出来的最后一位身份证号码
      if (value[value.length - 1] != last) {
        callback(new Error("你输入的身份证号非法"));
      }
      callback();
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.changeForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      userName:"",
      flag: false,
      registerFormVisible: false,
      registerForm: {
        name: "",
        pass: "",
        IdCard: "",
      },
      changeFormVisible: false,
      changeForm: {
        name: "",
        pass: "",
        checkPass: "",
      },
      rules: {
        name: [{ required: true, message: "请输入账号", trigger: "blur" }],
        pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
        IdCard: [{ validator: checkIdentitytionId, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
    };
  },
  watch: {
    nowData: function (now, old) {
      console.log("now", now);
    },
  },
  created() {
    this.userName = window.sessionStorage.getItem("userName");
    if (this.userName == "admin" || this.userName == "zs") {
      this.flag = true;
    }
  },
  methods: {
    // 注册
    register(formName, item) {
      console.log(item);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit!");
          axios
            .post("http://127.0.0.1:3000/login/addUser", {
              userName: item.name,
              userPwd: item.pass,
              userIdCard: item.IdCard,
            })
            .then((data) => {
              console.log(data);
              if (data.data.code == 200) {
                this.registerFormVisible = false;
                this.$router.push("/login");
              } else {
                this.$message.error(
                  "用户账号已注册，建议修改账号名称或身份证号"
                );
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 更改
    changeUser() {
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/login/changeUser",
        params: {
          userId: window.sessionStorage.getItem("userId"), //用户id
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            console.log("success", res.data.data);
            this.changeForm.name = res.data.data[0].userName;
            this.changeForm.pass = res.data.data[0].userPwd;
            this.changeFormVisible = true
          } else {
            console.log("未找到该用户", res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    update(formName, item) {
      console.log(item);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit!");
          axios
            .post("http://127.0.0.1:3000/login/updateUser", {
              userName: item.name,
              userPwd: item.pass,
              userId: window.sessionStorage.getItem("userId"),
            })
            .then((data) => {
              //  barterId = data.data.data.insertId;
              console.log(data);
              this.changeFormVisible = false;
              this.$router.push("/login");
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 退出登录
    exit() {
      console.log(1);
      localStorage.clear();
      window.sessionStorage.clear();
      this.$router.push("/login");
      //   console.log(window.sessionStorage.getItem("userName"),"yonghu");
      // console.log(window.sessionStorage.getItem("userId"),"yonghu");
    },
    formatDate(date) {
      var year = date.getFullYear();
      var month = this.format(date.getMonth() + 1);
      var day = this.format(date.getDate());
      var h = this.format(date.getHours());
      var m = this.format(date.getMinutes());
      // var s = this.format(date.getSeconds())
      // return year + '-' + month + '-' + da + ' ' + h + ':' + m + ':' + s
      return year + "-" + month + "-" + day + " " + h + ":" + m;
    },
    format(val) {
      return Number(val) < 10 ? "0" + val : "" + val;
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
</script>
<style scoped lang='less'>
.el-header {
  background-color: #b1d2bc;
  // #6fb677;
  // rgb(175 204 206);
  height: 70px !important;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-aside {
  background-color: #d6e6d5;
  // rgb(209 229 234);
}
.el-main {
  background-color: #e5eae4;
  // rgb(232 237 244);
  padding-top: 10px;
}
.el-container,
.home {
  height: 100%;
}
.el-menu a {
  text-decoration: none;
  font-size: 17px;
  font-weight: bold;
  color: gray;
  // color: white;
}
.el-menu-item .is-active,
.router-link-exact-active span {
  color: black;
}
</style>


